Categories
MongoDB Node.js Basics

Node.js Basics — MongoDB Promises and Callbacks

Spread the love

Node.js is a popular runtime platform to create programs that run on it.

It lets us run JavaScript outside the browser.

In this article, we’ll look at how to start using Node.js to create programs.

Promises and Callbacks

The MongoDB client has methods that return promises.

They’re async code that can have the status pending before it has the result.

Once it has a result, the it can be fulfilled if the operation is done successfully.

Otherwise, it has the rejected status.

For example, the updateOne method returns a promise.

We can use it by writing:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    await testCollection.deleteMany({})
    const result = await testCollection.insertMany([
      { "_id": 1, "name": "apples", "qty": 5, "rating": 3 },
      { "_id": 2, "name": "bananas", "qty": 7, "rating": 1 },
      { "_id": 3, "name": "oranges", "qty": 6, "rating": 2 },
      { "_id": 4, "name": "avocados", "qty": 3, "rating": 5 },
    ]);
    console.log(result)
    const updateResult = await testCollection
      .updateOne({ name: "apple" }, { $set: { qty: 100 } })
    console.log(updateResult);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We call updateOne with the await keyword so that we can get the resolved value once we have it.

updateOne returns a promise, so we can use the await keyword.

If we want to catch errors, then we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    await testCollection.deleteMany({})
    const result = await testCollection.insertMany([
      { "_id": 1, "name": "apples", "qty": 5, "rating": 3 },
      { "_id": 2, "name": "bananas", "qty": 7, "rating": 1 },
      { "_id": 3, "name": "oranges", "qty": 6, "rating": 2 },
      { "_id": 4, "name": "avocados", "qty": 3, "rating": 5 },
    ]);
    console.log(result)
    try {
      const updateResult = await testCollection
        .updateOne({ name: "apple" }, { $set: { qty: 100 } })
      console.log(updateResult);
    } catch (error) {
      console.log(`Updated ${res.result.n} documents`)
    }

} finally {
    await client.close();
  }
}
run().catch(console.dir);

to add a catch block to log any errors that’s raised from the rejected promise.

Callbacks

We can also use callbacks to get the result of an operation.

For example, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    await testCollection.deleteMany({})
    const result = await testCollection.insertMany([
      { "_id": 1, "name": "apples", "qty": 5, "rating": 3 },
      { "_id": 2, "name": "bananas", "qty": 7, "rating": 1 },
      { "_id": 3, "name": "oranges", "qty": 6, "rating": 2 },
      { "_id": 4, "name": "avocados", "qty": 3, "rating": 5 },
    ]);
    console.log(result)
    testCollection
      .updateOne({ name: "apple" }, { $set: { qty: 100 } }, (error, result) => {
        if (!error) {
          console.log(`Operation completed successfully`);
        } else {
          console.log(`An error occurred: ${error}`);
        }
      })
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We call updateOne with a callback in the 3rd argument.

This lets us get the async result with the callback instead of returning a promise.

Conclusion

The MongoDB client returns promises or we can use callbacks to get the result from an async operation.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *